/**
 * axios 二次封装
 */

import axios from 'axios';
import config from '../config/index'
import {
    ElMessage
} from 'element-plus';
const TOKEN_INVALID = 'token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常'
import router from '../router/index'
// 创建axios实例对象，添加全局配置
const service = axios.create({
    baseUrl: config.baseApi,
    timeout: 8000
})
// 请求拦截
service.interceptors.request.use((req) => {
    // TO-do
    const headers = req.headers
    if (headers.Authorization) headers.Authorization = '111'
    return req
})

//响应拦截
service.interceptors.response.use((res) => {
    const {
        code,
        data,
        msg
    } = res.data

    if (code == 200) {
        return data
    } else if (code == 40001) {
        ElMessage.error(TOKEN_INVALID)
        setTimeout(() => {
            router.push('/login')
        }, 1500)
        return Promise.reject(TOKEN_INVALID)
    } else {
        ElMessage.error(msg || NETWORK_ERROR)
        return Promise.reject(NETWORK_ERROR)
    }
})

/*
 * 核心函数
 */
function request(options) {
    options.method = options.method || 'get'

    if (options.method.toLowerCase() === 'get') {
        options.params = options.data
    }
    if (config.env === 'prod') {
        server.default.baseUrl = config.baseApi
    } else {
        server.default.baseUrl = config.moke?config.mokeApi:config.baseApi
    }
    return service(options)
}
['get', 'post', 'put', 'delete', 'patch'].forEach(method => {
    request[method] = (url, data, options) => {
        return request({
            url,
            data,
            method,
            ...options
        })
    }
})
export default request